package se.topshelf.golftracker.core.repository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import se.topshelf.golftracker.core.domain.BaseEntity;

import java.util.List;

/**
 *
 */
@Transactional(propagation = Propagation.REQUIRED)
public abstract class BaseRepositoryImpl<T extends BaseEntity>
        implements BaseRepository<T> {
    @Autowired
    private HibernateTemplate hibernateTemplate;
    private Class typeClass;

    protected BaseRepositoryImpl(T instance) {
        typeClass = instance.getClass();
    }

    public T get(String id) {
        return (T) hibernateTemplate.get(typeClass, id);
    }

    public <S extends BaseEntity> S get(Class<S> baseEntityClass, String id) {
        return hibernateTemplate.get(baseEntityClass, id);
    }

    public <S extends BaseEntity> void delete(S entity) {
        hibernateTemplate.delete(entity);
    }

    public <S extends BaseEntity> void saveOrUpdate(S entity) {
        hibernateTemplate.saveOrUpdate(entity);
    }

    public List<T> findAll() {
        return (List<T>) hibernateTemplate.loadAll(typeClass);
    }

    public <S extends BaseEntity> List<S> findAll(Class<S> baseEntityClass) {
        return hibernateTemplate.loadAll(baseEntityClass);
    }

    public void flush() {
        hibernateTemplate.flush();
    }

    public void clear() {
        hibernateTemplate.clear();
    }

    public <S extends BaseEntity> S merge(S entity) {
        return hibernateTemplate.merge(entity);
    }
}
